﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace wpf.Triage.Behavior
{
    /// <summary>
    /// 处理全局回车，方向键
    /// </summary>
    public class GridPressKeyBehavior : Behavior<Grid>
    {
        /// <summary>
        /// DataGrid附加事件  2022-03-28
        /// </summary>
        protected override void OnAttached()
        {
            AssociatedObject.KeyUp += AssociatedObject_KeyUp;
        }
        /// <summary>
        ///  全局回车事件转tab索引，左右方向键跳转 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AssociatedObject_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            try
            {
                var uie = e.OriginalSource as UIElement;
                TextBox tb = (TextBox)uie;
                if (tb == null)
                    return;
                if (!string.IsNullOrEmpty(tb.Text) && tb.TemplatedParent is WpfToolkit.AutoCompleteTextBox)
                    return;
                if (e.Key == Key.Enter || e.Key == Key.Right)
                {
                    uie.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
                    e.Handled = true;
                }
                else if (e.Key == Key.Left)
                {
                    uie.MoveFocus(new TraversalRequest(FocusNavigationDirection.Previous));
                    e.Handled = true;
                }
            }
            catch (System.Exception)
            {
                return;
            }
        }
          
        /// <summary>
        /// 行为移除
        /// </summary>
        protected override void OnDetaching()
        {
            AssociatedObject.KeyUp -= AssociatedObject_KeyUp;
        }
    }
}
